package cn.virens.cmpt.rabbit;

import java.io.IOException;
import java.util.Map;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;

public class RabbitConsumerProps implements AutoCloseable {
	private final Channel mChannel;

	// 判断消息是否已经应答
	private boolean isExpend = false;

	private BasicProperties properties;
	private Envelope envelope;

	private Boolean reply;
	private String mac;
	private String cmd;

	public RabbitConsumerProps(Channel mChannel, String consumerTag) {
		this.mChannel = mChannel;
	}

	public String getCmd() {
		return cmd;
	}

	public void setCmd(String command) {
		this.cmd = command;
	}

	public String getMac() {
		return mac;
	}

	public void setMac(String mac) {
		this.mac = mac;
	}

	public Boolean getReply() {
		return reply;
	}

	public void setReply(Boolean reply) {
		this.reply = reply;
	}

	public Envelope envelope() {
		return envelope;
	}

	public void setEnvelope(Envelope envelope) {
		this.envelope = envelope;
	}

	public BasicProperties properties() {
		return properties;
	}

	public void setProperties(BasicProperties properties) {
		this.properties = properties;
	}

	private long getDeliveryTag() {
		return envelope.getDeliveryTag();
	}

	public String getCorrelationId() {
		return properties.getCorrelationId();
	}

	public Map<String, Object> getHeaders() {
		return properties.getHeaders();
	}

	/**
	 * 确认消息
	 * 
	 * @param  multiple  是否多条
	 * @throws Exception
	 */
	public void basicAck(boolean multiple) throws IOException {
		this.mChannel.basicAck(getDeliveryTag(), multiple);
		this.isExpend = Boolean.TRUE.booleanValue();
	}

	/**
	 * 拒收消息
	 * 
	 * @param  requeue   返回队列
	 * @throws Exception
	 */
	public void basicReject(boolean requeue) throws IOException {
		this.mChannel.basicReject(getDeliveryTag(), requeue);
		this.isExpend = Boolean.TRUE.booleanValue();
	}

	/**
	 * 拒收消息(可多条)
	 * 
	 * @param  multiple  是否多条
	 * @param  requeue   返回队列
	 * @throws Exception
	 */
	public void basicNack(boolean multiple, boolean requeue) throws IOException {
		this.mChannel.basicNack(getDeliveryTag(), multiple, requeue);
		this.isExpend = Boolean.TRUE.booleanValue();
	}

	/**
	 * 回复消息-执行应答动作
	 * 
	 * @param  properties  消息属性
	 * @param  massage     消息内容
	 * @throws IOException
	 */
	public void basicReply(BasicProperties properties, byte[] massage) throws IOException {
		this.mChannel.basicPublish("", properties().getReplyTo(), properties, massage);
	}

	@Override
	public void close() throws Exception {
		if (!isExpend) basicAck(false);
	}

}
